#include <windows.h>
#include <stdio.h>

const DWORD BUFSIZE = 1024;
const DWORD PIPE_TIMEOUT = 5000;

int main()
{
    HANDLE hPipe = CreateNamedPipeW(L"\\\\.\\pipe\\Dbzhang800Pipe",
            PIPE_ACCESS_DUPLEX,
            PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
            PIPE_UNLIMITED_INSTANCES,
            BUFSIZE,
            BUFSIZE,
            PIPE_TIMEOUT,
            NULL);
    if (hPipe == INVALID_HANDLE_VALUE) {
        return -1;
    }

    for (;;) {
        if (ConnectNamedPipe(hPipe, NULL) || (GetLastError() == ERROR_PIPE_CONNECTED)) {
            DWORD cbBytesRead;
            char chRequest[BUFSIZE];
            bool fSuccess = ReadFile (hPipe, chRequest, BUFSIZE, &cbBytesRead, NULL);
            chRequest[cbBytesRead] = '\0';
            printf("Data Received: %s\n",chRequest);
            if (! fSuccess || cbBytesRead == 0) {
                break;
            }
            DisconnectNamedPipe(hPipe);
        } else {
            CloseHandle(hPipe);
            return -2;
        }
    }
    CloseHandle(hPipe);
    return 0;
}

